<script setup>
/**
 * & 文件引入区域
 */
import { ref, onMounted, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";

import {
  generateUnpaidItemOrder,
  generateUnpaidOrderByPi,
} from "@/server/api/itemApi";
import {
  deleteBuyerDataByIdAPI,
  faultAddressAIP,
  selectAllAddressAPI,
  updateBuyerDataByIdAPI,
} from "@/server/api/BuyerData";
import { generateUnpaidShopOrder } from "@/server/api/shopApi";

import { ToastFun } from "@/hook/toast";
import { getJWTFun } from "@/hook/jsrsasign";

import { orderStatus } from "@/stores/payStore";
import { useUseStore } from "@/stores/user";
import { countryList } from "@/data/countryList";

import { getLogisticsQuotation } from "@/server/api/logisticsQuotation";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 注册区
 */

/**
 * & 变量声明区
 */
const router = useRouter();
const route = useRoute();

/**
 * checked：控制支付方式
 * true为积分支付
 * false为pi支付
 */
const commodityInfo = ref()
let checked = ref(true);
let showBottom = ref(false); // 地址选择弹出层
let addressList = ref(); // 获取的地址列表
let selectAddress = ref(); // 选择的地址，默认第一个
let addressId = ref(); // 选择的地址Id
let unPaidOrderReq = ref(); // 生成未支付订单的请求头
let userId = useUseStore().userId; // 获取userId
let price = ref(0); // 渲染到页面的价格，只用于网店订单
const sumCount = ref(1)
const commoditySpecification = ref()

let postlist = ref([]); //获取快递名称
let postage = ref([]); //获取快递资金
let selectedDeliveryWay = ref(null); //获取选择器的值
let totalPost = ref(0); //存取总的邮费
let toCountryName = ref(null); //获取选择的国家名字
let tocountryEame = ref(null); //获取国家的英文名
let isCountry = ref(false); //判断国家的选择状态
let isPost = ref(false); //判断邮费的状态
let toCountryCode = ref(); //获取国家列表的code
let deaultImg = ref(null); //获取国旗的图片
let packageWeight = ref(500); //获取运输的货物重量,默认为500
//let isWarn = ref(false); //提示无重量或者无快递方式

// 将获得的首重续重以及额外的费用拆分开，并拿来计算得出最终的总邮费
let firstWeightFee = ref();
let continueWeightFee = ref();
let firstWeight = ref();
let firstWeightPrice = ref();
let continueWeight = ref();
let continueWeightPrice = ref();
let AddedServicesFee = ref();
let AddedServicesPrice = ref();

const id = ref(useUseStore().countryCode); //获取topBar传过来的参数

/**
 * & 函数区
 */
//获得后端对应的选项列表里的数据

console.log(id, "idididid");

const getInfo = async (img, country) => {
  deaultImg = img;
  toCountryCode = country.countryCode;
  // console.log(toCountryCode)
  tocountryEame = country.countryEName;
  //根据国家的代号名字来查找对应的快递名称
  toCountryName = country.countryName;
  console.log(toCountryName);
  const res = await getLogisticsQuotation(toCountryCode);
  console.log(res, "res");
  postlist.value = res.data;
  console.log(postlist.value, "postlist");
};


const totalPrice = computed(() => {
  // 如果价格为空或者不是有效数字，返回 0
  // const unitPrice = parseFloat(price.value) || 0;
  return (commodityInfo.value.price * sumCount.value).toFixed(2)
});

const isWarn = computed(() => {
  if (packageWeight.value == 0) {
    ToastFun("", { msg: t("MakesureOrder.weight2") });
    if (postlist.value.length == 0) {
      ToastFun("show", {
        msg: t("order.selectAddress2"),
      });
      router.push("/AddNewAddress");
    }
  } else {
    ToastFun("", {});
    // router.back();
  }
});

//改变根据不同的选项计算不同的邮费
const changePost = () => {
  isPost.value = true;

  //获取对应的邮费数据
  postage.value = postlist.value.filter(
    (item) => item.businessProducts === selectedDeliveryWay.value
  );
  console.log(postage.value[0], "postage");
  firstWeightFee.value = postage.value[0].firstWeightTariff;
  if (firstWeightFee.value !== null) {
    //将获取到的首重的重量和价钱分开来
    const match1 = firstWeightFee.value.match(/([\d.]+)\s*eCNY\/(\d+)\s*g/);
    if (match1.value !== null) {
      firstWeightPrice.value = match1[1];
      firstWeight.value = match1[2];
      console.log(firstWeightPrice, 1111);
      console.log(firstWeight);
    }
  }

  continueWeightFee.value = postage.value[0].wrenewalUnitPrice;
  // 将续重的重量跟价钱分开来
  if (continueWeightFee.value !== null) {
    const match2 = continueWeightFee.value.match(/([\d.]+)\s*eCNY\/(\d+)\s*g/);
    console.log(111111111);
    console.log(match2, "ssssssss");
    if (match2 !== null) {
      continueWeightPrice.value = match2[1];
      continueWeight.value = match2[2];
      console.log(22222);
      console.log(continueWeight, 2121);
    }
  }

  AddedServicesFee.value = postage.value[0].valueAddedServices;
  if (AddedServicesFee.value !== null) {
    const match3 = AddedServicesFee.value.match(/\d+(\.\d+)?/);
    if (match3.value !== null) {
      AddedServicesPrice.value = match3[0];
      console.log(AddedServicesPrice, "ahahahah");
    }
  }

  //计算总邮费
  totalPost = computed(() => {
    let total = 0;
    if (
      selectedDeliveryWay.value !== null &&
      firstWeightFee.value !== null &&
      AddedServicesFee.value !== null &&
      continueWeightFee.value !== null
    ) {
      if (Number(packageWeight.value) === 0 || postlist.value.length === 0) {
        total = 0;
      } else if (Number(packageWeight.value) <= Number(firstWeight.value)) {
        total =
          Number(firstWeightPrice.value) + Number(AddedServicesPrice.value);
      } else if (
        Number(packageWeight.value) > Number(firstWeight.value) &&
        Number(packageWeight.value) - Number(firstWeight.value) <
        Number(continueWeight.value)
      ) {
        total =
          Number(firstWeightPrice.value) +
          Number(continueWeightPrice.value) +
          Number(AddedServicesPrice.value);
      } else if (
        Number(packageWeight.value) - Number(firstWeight.value) >=
        Number(continueWeight.value)
      ) {
        total =
          Number(firstWeightPrice.value) +
          Number(continueWeightPrice.value) *
          Math.floor(
            (Number(packageWeight.value) - Number(firstWeight.value)) /
            Number(continueWeight.value)
          ) +
          Number(AddedServicesPrice.value);
      }
    }
    return Number(total.toFixed(2));
  });
  console.log(totalPost.value, "total");
};



// 跳转支付页面
const toItemPay = () => {
  // 获取订单类型
  let type = orderStatus().orderType;

  if (type == "item") {
    // 如果为真即积分支付
    if (checked.value) {
      // ! 判断如果类型为网店类型，则调用网店的订单接口
      unPaidItemOrderFun();
    }
    // 否则为PI支付
    else {
      ItemOrderByPIFun();
    }
  } else if (type == "shop") {
    // ! 判断如果类型为实体店类型，则调用实体店的订单接口
    unPaidShopOrderFun();
  }
};

// // 获取用户地址列表
// const getAllAddress = async () => {
//   ToastFun("Loading", { duration: 1000 });
//   let { data } = await selectAllAddressAPI(userId);

//   if (data.code === 200) {
//     if (data.data.length > 0) {
//       ToastFun("", {});
//       addressList.value = data.data;
//       selectAddress.value = addressList.value[0];
//       addressId.value = addressList.value[0].buyerDataId;

//       console.log("地址列表", addressList.value);
//     } else {
//       ToastFun("show", { msg: "no address" });
//       router.back();
//     }
//   } else {
//     ToastFun("", {});
//     router.back();
//   }
//   // console.log("选择的地址", selectAddress.value);
// };

// // 选择地址方法
// const selectAddFun = (id) => {
//   // 隐藏弹框
//   addressId.value == id
//     ? (showBottom.value = true)
//     : (showBottom.value = false);

//   // 控制样式
//   addressId.value = id;
//   modifyAddress(id); //传参
//   // 找到下标
//   let index = addressList.value.findIndex((item) => item.buyerDataId == id);
//   // 赋值选择的地址，以渲染到页面
//   selectAddress.value = addressList.value[index];
//   console.log("选择的地址", selectAddress.value);
// };





// 生成实体店未支付订单接口
const unPaidShopOrderFun = async () => {
  // 将支付类型改为网店，以调用网店的接口

  const data = {
    commodityId: commodityInfo.value.commodityId,
    shopId: commodityInfo.value.shopId,
    number: sumCount.value,
    transactionAmount: totalPrice.value,
    uid: userId
  }

  let token = getJWTFun(data);
  console.log(token);
  ToastFun("Loading", { duration: 1000 });
  let res = await generateUnpaidShopOrder(token);

  if (res.data.code == 200) {
    // 获取订单id
    let orderId = res.data.data;
    // 解构传来的信息
    let { commodityId, number, transactionAmount, uid } = data
    // 生成的支付订单请求体，存入公共管理库
    orderStatus().shopPayReq = {
      commodityId,
      number,
      orderId,
      transactionAmount,
      uid,
    };

    console.log("生成支付接口的请求头", orderStatus().shopPayReq);

    ToastFun("", {});
    router.push({ path: "/shopPay" });
  } else {
    ToastFun("", {});
  }
};

// // 监听支付方式选择：checked
// watch(
//   () => checked.value,
//   (newVl) => {
//     // 判断用户选择的支付方式，切换订单的价格

//     price.value = newVl
//       ? unPaidOrderReq.value.itemOrderDetailDTOList[0].price
//       : unPaidOrderReq.value.itemOrderDetailDTOList[0].piPrice;
//   }
// );

onMounted(() => {
  if (route.query.commodityInfo) {
    commodityInfo.value = JSON.parse(route.query.commodityInfo);
    console.log(commodityInfo.value, "commodityInfo");

    // price.value = commodityInfo.value.price;
    // 判断订单类型是否为实体店
    let type = orderStatus().orderType;
    console.log(type, "type", orderStatus().shopOrderReq);

    unPaidOrderReq.value = orderStatus().shopOrderReq;

    console.log(unPaidOrderReq.value);
  }

});
</script>

<template>
  <div class="contain">
    <!-- 导航栏 -->
    <div class="nav">
      <div class="left" @click="$router.back()">
        <img src="/images/cart/back.png" />
      </div>
      <div class="title">{{ $t("order.confirmOrder") }}</div>
    </div>

    <div v-if="commodityInfo && commodityInfo.commodityName">
      <!-- 商品信息 -->
      <div class="product-information">
        <!-- 商品名 -->
        <div class="name">{{ commodityInfo.commodityName }}</div>
      </div>

      <!-- 支付方式 -->
      <div class="PointPayment">
        <div class="item">
          <div class="title">{{ $t("order.pointPay") }}</div>
          <div :class="['checkbox', checked ? 'con' : '']" @click="checked = true">
            <img src="/images/Home/check.png" alt="" class="btn" />
          </div>
        </div>
      </div>

      <!-- 总价 -->
      <div class="GoodsPrice">
        <div class="item">
          {{ $t("order.scheduledInfo") }}
          <span>
            {{ commodityInfo.commodityName }}
          </span>
        </div>
        <div class="item">
          单价
          <span>
            {{ commodityInfo.price }}
          </span>
        </div>
        <div class="item">
          数量
          <span>
            <van-stepper v-model="sumCount" integer min="1" max="99" />
          </span>
        </div>
      </div>

      <!-- 合计 -->
      <div class="Total">
        <div>{{ $t("order.total") }}</div>
        <span>
          {{ totalPrice }}</span>
      </div>
    </div>
    <!-- 提交订单，跳转支付页面 -->
    <div class="Submit" @click="toItemPay">{{ $t("order.submit") }}</div>
  </div>
</template>

<style lang="scss" scoped>
// 容器
.contain {
  width: 100vw;
  min-height: 100vh;
  background-color: rgba(235, 236, 237, 1);
  font-family: "PingFang SC";

  padding-top: 60rem;
  box-sizing: border-box;
}

// 导航栏
.nav {
  padding: 16rem 16rem;

  display: flex;
  align-items: center;

  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;

  background-color: rgba(235, 236, 237, 1);

  .left {
    display: flex;
    align-items: center;
    justify-content: center;

    width: 24rem;
    height: 24rem;
    line-height: 24rem;

    img {
      width: 6rem;
      height: 12rem;
    }
  }

  .title {
    height: 28rem;
    margin: 0 20rem;
    font-size: 20rem;
    font-weight: 500;
    line-height: 28rem;
    text-align: center;
  }
}

.product-information {
  background-color: #fff;
  border-radius: 12rem;
  font-size: 16rem;
  padding: 12rem 12rem 10rem;
  margin: 12rem 16rem;

  .name {
    max-width: 309rem;
    max-height: 48rem;

    font-size: 20rem;
    font-weight: 500;
    line-height: 28rem;
    color: rgba(51, 51, 51, 1);

    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;

    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .to {
    display: flex;
    font-size: 12rem;
    margin: 55rem 0 18rem;
    align-items: center;

    .title-to {
      max-width: 50rem;
      color: #ccc;
      padding-left: 3rem;
    }

    .text-down {
      font-size: 14rem;
      color: #666;
      margin-left: 12rem;

      .text-to {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .seller {
        display: flex;
        font-size: 14rem;

        .sellphome {
          margin-top: 3rem;
          margin-left: 7rem;
          font-weight: 600;
        }
      }
    }
  }
}

.PointPayment {
  padding: 10rem 0;
  margin: 12rem 16rem;
  border-radius: 12rem;
  background: #fff;

  >.item {
    height: 50rem;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      margin: 0 12rem;
      font-size: 16rem;
      font-weight: 500;
      color: rgba(51, 51, 51, 1);
    }

    >.checkbox {
      width: 14rem;
      height: 14rem;
      margin: 0 12rem;

      border: 1rem solid #c9c9c9;
      border-radius: 50%;

      display: flex;
      justify-content: center;
      align-items: center;

      >img {
        width: 8rem;
        margin-top: -2rem;
        display: none;
      }

      &.con {
        background-color: rgba(100, 46, 142, 1);
        border-color: rgba(100, 46, 142, 1);

        >img {
          display: block;
        }
      }
    }
  }
}

.GoodsPrice {
  margin: 12rem 16rem;
  padding: 16rem 12rem;

  border-radius: 12rem;
  background: rgba(255, 255, 255, 1);

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;

    padding: 8rem 0;
    font-size: 16rem;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);

    font-size: 16rem;
    font-weight: 500;
    line-height: 22rem;
    color: #333;
  }

  .buytip {
    color: red;
    font-size: 10rem;
  }
}

.Total {
  height: 66rem;

  border-radius: 12rem;
  background: rgba(255, 255, 255, 1);
  margin: 12rem 16rem;
  padding: 0 12rem;

  font-size: 20rem;
  font-weight: 500;
  color: rgba(51, 51, 51, 1);

  display: flex;
  align-items: center;
  justify-content: space-between;

  position: relative;
  margin-bottom: 60rem;

  span {
    right: 12rem;
    font-size: 24rem;
    color: rgba(100, 46, 142, 1);
  }
}

.Submit {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;

  border-radius: 8rem;
  background: #642e8eff;

  margin: 0 16rem 20rem;

  font-size: 20rem;
  line-height: 50rem;
  text-align: center;
  font-weight: 500;
  color: #fff;
}

.popup {
  :deep(.van-popup) {
    border-radius: 15rem 15rem 0 0;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .addersList {
    padding-top: 20rem;

    li {
      border: 1rem solid #ccc;
      box-sizing: border-box;
      width: 90%;
      background-color: #ffffff;
      border-radius: 10rem;
      margin: 10rem auto 15rem;
      padding: 10rem 15rem;

      p {
        width: 70%;
        font-size: 16rem;
        line-height: 30rem;
      }

      .footer_en {
        display: flex;
        justify-content: space-between;

        .info {
          color: #ccc;
          display: flex;
          font-size: 16rem;
          line-height: 30rem;

          .name {
            margin-right: 10rem;
          }
        }

        .update {
          max-width: 70rem;
          white-space: nowrap;

          color: #fff;
          padding: 0rem 20rem;
          background: #642e8eff;
          border: 2rem solid;
          border-radius: 5rem;
          font-size: 15rem;
        }

        .text_right {
          width: 58rem;
          height: 36rem;
          text-align: center;
          line-height: 36rem;
          white-space: nowrap;
          color: #642e8eff;
          border: 1rem solid;
          border-radius: 5rem;
        }
      }

      &.border {
        border: 1rem solid #642e8eff;
      }
    }
  }
}
</style>
